#include <openssl/bn.h>

// a^p mod m
int exp_mod_bn(const char *a, const char *p,
		const char *m, char **rez){
	int rc = 0;

	BIGNUM *num = NULL;
	BN_dec2bn(&num, a);

	BIGNUM *exp = NULL;
	BN_dec2bn(&exp, p);

	BIGNUM *mod = NULL;
	BN_dec2bn(&mod, m);

	BIGNUM *r = BN_new();
	BN_CTX *ctx = BN_CTX_new();
	if(ctx == NULL)
		return 1;

	if (!BN_mod_exp(r, num, exp, mod, ctx)) {
		return 1;
	}

	*rez = BN_bn2dec(r);
	if (!rez)
		return 1;

	BN_CTX_free(ctx);

	BN_free(r);
	BN_free(mod);
	BN_free(exp);
	BN_free(num);

	return rc;
}
